package com.own.component.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

/**
 * FileUtil
 *
 * @author chenxueli
 * @date 2021/3/10 14:54
 */
@Slf4j
public final class FileUtil {

    /**
     * 临时文件夹名称
     */
    public final static String TEMP_FILE_NAME = "temp";
    /**
     * 文件根目录名称
     */
    public final static String FILE_ROOT_NAME = "files";
    /**
     * 文件上传目录
     */
    public final static String FILE_UPLOAD_NAME = "upload";
    /**
     * 备份文件夹名称
     */
    public final static String FILE_BACKUP_NAME = "backup";

    /**
     * 最大的临时文件数量
     */
    private final static int MAX_TEMP_FILE = 5;

    /**
     * 创建并生成文件夹
     *
     * @param path 路径
     */
    public static void generatePath(String path) {
        var file = new File(path);
        if (!file.exists()) {
            var flag = file.mkdirs();
            if (!flag) {
                log.info("文件夹创建失败：{}", path);
            }
        }
    }

    /**
     * 获取文件md5
     *
     * @param path 文件路径
     * @return md5
     */
    public static String md5Hex(String path) {
        try {
            return DigestUtils.md5Hex((new FileInputStream(path)));
        } catch (IOException e) {
            return "";
        }
    }

    /**
     * 获得临时文件目录
     *
     * @return java.lang.String
     * @author Enzo
     * @date 2019-9-16
     **/
    public static String getTempFolder() {
        var tempFolder = new File(getStaticFileFolder(), TEMP_FILE_NAME);
        deleteTempFile();
        return tempFolder.getAbsolutePath().concat(File.separator);
    }

    /**
     * 获得静态资源文件地址
     *
     * @return java.io.File
     * @author Enzo
     * @date 2021-3-11
     **/
    public static File getStaticFileFolder() {
        var webappRoot = System.getProperty("user.dir");
        return new File(webappRoot, FILE_ROOT_NAME);
    }

    /**
     * 获得备份目录
     *
     * @return java.lang.String
     * @author Enzo
     * @date 2020-5-6
     **/
    public static String getBackupFolder() {
        File file = new File(getStaticFileFolder(), FILE_BACKUP_NAME);
        return file.getAbsolutePath().concat(File.separator);
    }

    /**
     * 获得上传目录
     *
     * @return java.lang.String
     * @author Enzo
     * @date 2020-5-6
     **/
    public static String getUploadFolder() {
        File file = new File(getStaticFileFolder(), FILE_UPLOAD_NAME);
        return file.getAbsolutePath().concat(File.separator);
    }

    /**
     * 删除文件及文件夹
     *
     * @param file 删除的文件文件夹
     * @author Enzo
     * @date 2019-7-26
     **/
    public static void deleteFile(File file) {
        if (!file.exists()) {
            return;
        }
        if (file.isDirectory()) {
            String folderPath = file.getAbsolutePath();
            var array = file.list();
            if (array != null) {
                for (String fileName : array) {
                    File childrenFile = new File(folderPath + File.separator + fileName);
                    deleteFile(childrenFile);
                }
            }
        }
        var flag = file.delete();
        log.info("删除文件（夹）{}:{}", file.getAbsolutePath(), flag);
    }

    /**
     * 删除临时文件夹下的文件或文件夹，保留最后最新的3个文件或文件夹
     *
     * @author Enzo
     * @date 2019-7-26
     **/
    public static void deleteTempFile() {
        var tempRootFolder = new File(getStaticFileFolder(), TEMP_FILE_NAME);
        var exists = tempRootFolder.exists();
        String[] list = exists ? tempRootFolder.list() : null;
        if (list == null) {
            return;
        }
        if (list.length > 1) {
            Arrays.stream(list).limit(MAX_TEMP_FILE)
                    .map(Integer::parseInt)
                    .sorted(Integer::compare)
                    .forEach(item -> {
                        log.info("删除临时文件：{}", item);
                        var childrenFile = new File(tempRootFolder, item + "");
                        deleteFile(childrenFile);
                    });
        }
    }

    /**
     * 文件写到本地
     *
     * @param folder      文件夹
     * @param fileName    文件名称
     * @param inputStream 文件流
     * @author chenxueli
     * @date 2022-06-15 03:14:15
     */
    public static void write(String folder, String fileName, InputStream inputStream) {
        // 生成文件夹
        generatePath(folder);
        // 写入文件
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(folder + "/" + fileName);
            byte[] b = new byte[1024];
            while ((inputStream.read(b)) != -1) {
                fileOutputStream.write(b);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
